package com.xiaoxu.intranetweb.util;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * excel操作工具类
 * @author xiaoxu
 * @date 2023/2/03 09:00
 * @version 1.0
 * @since 1.0
 */
@Component
public class CustomAnnotateUtil {
    @Autowired
    private WebFunctionUtil webFunctionUtil;
    @Autowired
    private UserInfoDao userInfoDao;

    @Aspect
    @Component
    public class CheckPermissionAspect {
        @Autowired
        private WebFunctionUtil webFunctionUtil;
        @Before("@annotation(permissionCheck)")
        public void checkPermission(JoinPoint joinPoint, PermissionCheck permissionCheck) throws Exception {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            String token = request.getHeader("Authorization");
            Map userPermissionWeb = userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString());
            Map permission = webFunctionUtil.webFunction(userPermissionWeb, permissionCheck.value());
            // 权限检查逻辑
            if (permission.get("code").equals(0)) {
                String errorMessage = permission.get("msg").toString();
                throw new PermissionDeniedException(errorMessage);
            }
        }
        public class PermissionDeniedException extends Exception {
            public  PermissionDeniedException(String message) {
                super(message);
            }
        }
    }
}
